﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Cassini;
using TechTalk.SpecFlow;
using WatiN.Core;

namespace BDD.TicTacToe.Acceptance.Tests.Utilities
{
    public class WebBrowser
    {
        public const string RelativePath = @"BDD.TicTacToe.Ui.Mvc";

        public const int Port = 8092;

        public static Browser Current
        {
            get
            {
                if (!ScenarioContext.Current.ContainsKey("browser"))
                    ScenarioContext.Current["browser"] = new IE();
                return (Browser)ScenarioContext.Current["browser"];
            }
        }


        public static void Stop()
        {
            if (ScenarioContext.Current.ContainsKey("browser"))
                Current.Close();
        }

        protected static Server WebServer { get; private set; }

        private static string GetPhysicalPath()
        {
            var dir = Directory.GetCurrentDirectory();

            var index = dir.LastIndexOf("BDD.TicTacToe.Acceptance.Tests");

            dir = dir.Remove(index);

            return Path.Combine(dir, RelativePath);
        }

        public static void InitializeBrowser()
        {
            // Initialize the web server
            WebServer = new Server(Port, "/", GetPhysicalPath());

            WebServer.Start();
        }

        public static void ShutdownBrowser()
        {
            WebServer.Stop();
        }
    }
}
